'use strict';
/**
 * Created by deng on 16-3-25.
 * @author Yud
 */

angular.module('metalabOperationApp').factory('Passport', ['$rootScope', '$state', '$http', 'MetaRemind', 'MetaResources', '$q',
    function ($rootScope, $state, $http, MetaRemind, MetaResources, $q) {

        var funs = {};

        funs.init = function () {


            /**
             * 在运维系统中使用localstorage作为登录token存贮的载体
             */
            //var sso = xdLocalStorage;
            var sso = localStorage;

            ///**
            // * xdLocalStorage 初始化
            // * 具体使用请参考xdLocalStorage文档
            // */
            //sso.init(
            //    {
            //        /* required */
            //        iframeUrl: 'https://rawgit.com/ofirdagan/cross-domain-local-storage/master/app/views/cross-domain-local-storage.html',
            //        //an option function to be called right after the iframe was loaded and ready for action
            //        initCallback: function () {
            //            console.log('Got iframe ready');
            //
            //            // 检测是否包含USER_TOKEN字段，如果有则广播登录事件.
            //            sso.getItem('USER_TOKEN', function (data) {
            //                if (data.value && data.value !== 'null') {
            //                    $rootScope.$broadcast('signIn', {token: data.value});
            //                    $rootScope.$apply();
            //                }
            //            });
            //        }
            //    }
            //);

            $rootScope.passportPromise = $q.defer();

            //注册逻辑
            $rootScope.$on('signIn', function (event, args) {
                $rootScope.USER_TOKEN = args.token;
                $http.defaults.headers.common['X-Token'] = $rootScope.USER_TOKEN;
                MetaResources.user.get({id: '_self'}, function (data) {
                    $rootScope.USER = data;
                    sso.setItem('USER_TOKEN', $rootScope.USER_TOKEN);
                    $rootScope.passportPromise.resolve('yes');
                }, function () {
                    $rootScope.$broadcast('signOut');
                });
            });

            $rootScope.$on('signOut', function () {
                // 清除 $rootScope的默认值
                delete $rootScope.USER_TOKEN;
                // 清除 sso 单点登录
                sso.removeItem('USER_TOKEN');
                // 刷新页面

                $state.go('meta.visitor');
            });

            if (sso.getItem('USER_TOKEN')) {
                $rootScope.$broadcast('signIn', {token: sso.getItem('USER_TOKEN')});
            } else {
                $rootScope.$broadcast('signOut');
                $rootScope.passportPromise.resolve('sorry');
            }


        };

        funs.isSignIn = function () {
            return $rootScope.USER_TOKEN;
        };

        funs.signIn = function (passport) {
            passport['validPeriod'] = 3600 * 24 * 7;
            //passport['validPeriod'] = 7;
            MetaResources.passport.signIn({}, passport, function (data) {
                MetaRemind.success('登录成功');
                $rootScope.$broadcast('signIn', data);
                $state.go('meta.permission.system.announcement');
            }, function (error) {
                MetaRemind.serverError(error);
                $rootScope.$broadcast('signOut');
            });
        };

        funs.signOut = function () {
            $rootScope.$broadcast('signOut');
        };

        return funs;
    }]);
